package com.cts.tmall.app.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cts.tmall.app.request.R;
import com.cts.tmall.app.response.PropSpecResponse;
import com.cts.tmall.app.response.SkuResponse;
import com.cts.tmall.biz.service.PropService;
import com.cts.tmall.biz.service.SkuService;
import com.cts.tmall.biz.service.SpecService;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.Prop;
import com.cts.tmall.dal.entity.Sku;
import com.cts.tmall.dal.entity.Spec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/prop")
public class PropController {

    @Autowired
    PropService propService;

    @Autowired
    SkuService skuService;

    @Autowired
    SpecService specService;

    @PostMapping("add")
    public R add(@RequestBody Prop prop) {
        if (StrUtil.isBlank(prop.getPropName())) {
            log.error("属性名称不能为空");
            throw new SystemException(RspCode.FAILURE_SYSTEM);
        }
        if (StrUtil.isBlank(prop.getGoodsNo())) {
            log.error("商品编号不能为空");
            throw new SystemException(RspCode.FAILURE_SYSTEM);
        }
        if (propService.count(new QueryWrapper<Prop>().eq("goods_no", prop.getGoodsNo())) > 1) {
            log.error("属性不能超过2个");
            throw new SystemException(RspCode.FAILURE_SYSTEM);
        }
        Snowflake snowflake = IdUtil.createSnowflake(1L, 1L);
        String no = String.valueOf(snowflake.nextId());
        prop.setPropNo(no);
        propService.save(prop);
        List<PropSpecResponse> propSpecResponseList = propService.getPropSpec(prop.getGoodsNo());
        List<SkuResponse> skuResponseList = skuService.getSkuList(prop.getGoodsNo());
        return R.ok().put("propList", propSpecResponseList).put("skuList", skuResponseList);
    }

    @PostMapping("del")
    public R del(@RequestBody Prop prop) {
        propService.remove(new QueryWrapper<Prop>().eq("prop_no", prop.getPropNo()));
        specService.remove(new QueryWrapper<Spec>().eq("prop_no", prop.getPropNo()));
        skuService.reCreateSku(prop.getGoodsNo());
        List<PropSpecResponse> propSpecResponseList = propService.getPropSpec(prop.getGoodsNo());
        List<SkuResponse> skuResponseList = skuService.getSkuList(prop.getGoodsNo());
        return R.ok().put("propList", propSpecResponseList).put("skuList", skuResponseList);
    }
}
